package be.castanea.client.view.ingame;

import be.castanea.client.CastaneaClient;
import be.castanea.client.model.Self;
import be.castanea.client.model.World;
import be.castanea.client.util.MapLoader;
import com.jme.light.DirectionalLight;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.state.CullState;
import com.jme.scene.state.LightState;
import com.jme.scene.state.ZBufferState;
import com.jme.system.DisplaySystem;
import com.jmex.game.state.BasicGameState;

/**
 * Castanea
 * 2009
 * @author Geert van Leemputten, Steven Rymenans, Bart Van Hooydonck
 */
public class IngameState extends BasicGameState {

    public IngameState() {
        super("INGAME");
        loadGame();
        setActive(true);
    }

    private void loadGame() {
        ZBufferState buf = DisplaySystem.getDisplaySystem().getRenderer().createZBufferState();
        buf.setEnabled(true);
        buf.setFunction(ZBufferState.TestFunction.LessThanOrEqualTo);
        rootNode.setRenderState(buf);

        CullState cs = DisplaySystem.getDisplaySystem().getRenderer().createCullState();
        cs.setCullFace(CullState.Face.Back);
        rootNode.setRenderState(cs);

        buildLighting();

        //update the scene graph for rendering
        rootNode.updateGeometricState(0.0f, false);
        rootNode.updateRenderState();

        MapLoader.loadMap("zone1", rootNode);
        Self.loadCharacter(CastaneaClient.getLoginState().getUsername(), rootNode);
    }

    @Override
    public void update(float interpolation) {
        World.getInstance().update(interpolation);
        rootNode.updateGeometricState(interpolation, false);
    }

    @Override
    public void render(float tpf) {
        DisplaySystem.getDisplaySystem().getRenderer().clearBuffers();
        DisplaySystem.getDisplaySystem().getRenderer().draw(rootNode);
    }

    @Override
    public void cleanup() {
    }

    private void buildLighting() {
        DirectionalLight light = new DirectionalLight();
        light.setDiffuse(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f));
        light.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f));
        light.setDirection(new Vector3f(1, -1, 0));
        light.setEnabled(true);

        LightState lightState = DisplaySystem.getDisplaySystem().getRenderer().createLightState();
        lightState.setEnabled(true);
        lightState.attach(light);
        rootNode.setRenderState(lightState);
    }
}
